package com.xq.interceptor;

import cn.hutool.crypto.SecureUtil;
import com.google.common.collect.Lists;
import com.xq.demo.Test9;
import com.xq.entity.UserInfo;
import com.xq.exception.BizException;
import com.xq.utils.MD5Sign;
import lombok.extern.log4j.Log4j2;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.*;

@Component
@Log4j2
public class LoginInterceptor implements HandlerInterceptor {

    String appSercret="aea43111aa87807fb79939b28256b929";

    @Autowired
    private RedisTemplate redisTemplate;
        /**
     * 预处理回调方法，实现处理器的预处理
     * 返回值：true表示继续流程；false表示流程中断，不会继续调用其他的拦截器或处理器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String accessToken = request.getHeader("accessToken");//访问token
        String timestamp = request.getHeader("timestamp");//时间搓
        String sign = request.getHeader("sign");//签名
        if(StringUtils.isBlank(accessToken)){
            throw new BizException(400,"token不存在");
        }
        if(StringUtils.isBlank(timestamp)){
            throw new BizException(400,"timestamp不存在");
        }
        if(StringUtils.isBlank(sign)){
            throw new BizException(400,"签名不存在");
        }
        long currentTime = System.currentTimeMillis();
        long timestampLong =Long.parseLong(timestamp);
        if((currentTime-timestampLong)>500000){
            throw new BizException(400,"请求超时");
        }
        List list = Lists.newArrayList();
        list.add(accessToken);
        list.add(timestamp);
        list.add(appSercret);
        String str = StringUtils.join(list,"|");
        //String a = accessToken+"|"+timestamp+"|"+appSercret;
        String signServer = SecureUtil.md5(str);
        if(!signServer.equals(sign)){
            throw new BizException(400,"签名失败");
        }

        UserInfo userInfo = (UserInfo)redisTemplate.opsForValue().get("access_token_"+accessToken);
        if(userInfo==null){
            throw new BizException(402,"token失效,请重新登录");
        }
        return true;
    }

    /**
     * 后处理回调方法，实现处理器（controller）的后处理，但在渲染视图之前
     * 此时我们可以通过modelAndView对模型数据进行处理或对视图进行处理
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }
    /**
     * 整个请求处理完毕回调方法，即在视图渲染完毕时回调，
     * 如性能监控中我们可以在此记录结束时间并输出消耗时间，
     * 还可以进行一些资源清理，类似于try-catch-finally中的finally，
     * 但仅调用处理器执行链中
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }



}
